package com.kajespero.webapp.controller.user;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.kajespero.model.UserBean;
import com.kajespero.service.user.impl.UserServiceImpl;
import com.kajespero.vo.UserVO;
import com.kajespero.webapp.AttributesConstants;
import com.kajespero.webapp.controller.commons.AbstractController;

@Controller
@RequestMapping("/user")
public class UserController extends
		AbstractController<UserServiceImpl, UserBean> {
	
	private static final Log LOG = LogFactory.getLog(UserController.class);

	@Override
	@RequestMapping(value = "/create_user")
	public ModelAndView create() {
		ModelAndView modelAndView = new ModelAndView("create_user");
		UserBean user = getService().createNewBean();
		modelAndView.addObject("user", user);
		return modelAndView;
	}

	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/save_user", method = RequestMethod.POST)
	public void saveOrUpdate(@ModelAttribute("user") UserBean user , BindingResult result,
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		UserBean oldUser = getService().find(user.getId());
		if (oldUser != null) {
			user.setKey(oldUser.getKey());
		}
		getService().saveOrUpdate(user);

		List<UserVO> users = (List<UserVO>) request.getSession()
				.getServletContext()
				.getAttribute(AttributesConstants.USERS_ATTRIBUTES);
		String path = "/administration";
		if (users.isEmpty()) {
			path = "/create_administration";
			request.getSession().setAttribute(
					AttributesConstants.ADMINISTRATOR, user);
		}
		mergeUsers(users, user);
		request.getSession().getServletContext()
				.setAttribute(AttributesConstants.USERS_ATTRIBUTES, users);

		String req = response.encodeRedirectURL("/index?"
				+ AttributesConstants.PATH + "=" + path);
		try {
			response.sendRedirect(req);
		} catch (IOException e) {
			LOG.error("IOException " + e.getMessage(), e);
		}

	}

	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delete_user", method = RequestMethod.POST)
	public void delete(HttpServletRequest request) {
		Long userId = Long.decode(request.getParameter("id"));
		Collection<UserVO> users = (Collection<UserVO>) request.getSession()
				.getServletContext()
				.getAttribute(AttributesConstants.USERS_ATTRIBUTES);
		for (UserVO userVO : users) {
			if (userVO.getId().intValue() == userId.intValue()) {
				users.remove(userVO);
				break;
			}
		}
		request.getSession().getServletContext()
				.setAttribute(AttributesConstants.USERS_ATTRIBUTES, users);
		getService().delete(userId);
	}

	@Override
	@RequestMapping(value = "/update_user")
	public ModelAndView update(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("create_user");
		Long userId = Long.decode(request.getParameter("id"));
		UserBean user = getService().find(userId);
		modelAndView.addObject("user", user);
		return modelAndView;
	}
	
	@RequestMapping(value = "/login")
	public ModelAndView login(){
		ModelAndView modelAndView = new ModelAndView("login");
		return modelAndView;
	}
	
	@RequestMapping(value = "/authentificate", method = RequestMethod.POST)
	public void authentificate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String login = (String) request.getParameter("login");
		String password = (String) request.getParameter("password");
		UserBean admin = getService().findByAuthentificate(login, password);
		String req = response.encodeRedirectURL("/");
		if( admin != null){
			request.getSession().setAttribute(
					AttributesConstants.ADMINISTRATOR, admin);
			req = response.encodeRedirectURL("/index?path=/administration");
		}
		response.sendRedirect(req);
	}
	
	@RequestMapping(value = "/rest/getAllUsers", method=RequestMethod.POST)
	public ModelAndView getAllUsers(@RequestBody LinkedHashMap<String, Serializable> map){
		ModelAndView modelAndView = new ModelAndView();
		if(checkCredential(map)){
			modelAndView.addObject("users", getService().findAll());
		}
		return modelAndView;
	}
	
	@RequestMapping(value="/rest/saveUser", method=RequestMethod.POST)
	public void saveOrUpdate(@RequestBody LinkedHashMap<String, Serializable> map){
		if(checkCredential(map)){
			UserBean user = convertJsonObject(map);
			getService().saveOrUpdate(user);
		}
	}
}